package com.isyscore.service.admin.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.isyscore.dto.sys.AddDeptForm;
import com.isyscore.dto.sys.DeptTreeDto;
import com.isyscore.dto.sys.ListDeptForm;
import com.isyscore.entity.admin.SysDept;
import com.isyscore.entity.admin.SysUser;
import com.isyscore.exception.FjMesException;
import com.isyscore.mapper.admin.SysDeptMapper;
import com.isyscore.service.admin.SysDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author LGL
 * @since 2024年10月25日
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Override
    public List<DeptTreeDto> getDeptList(ListDeptForm form) {
        List<SysDept> deptList = baseMapper.getDeptList(form);

        if (CollUtil.isEmpty(deptList)) {
            return Collections.emptyList();
        }

        Map<Long, DeptTreeDto> deptMap = deptList.stream()
                .map(dept -> {
                    DeptTreeDto dto = BeanUtil.toBean(dept, DeptTreeDto.class);
                    dto.setChildren(new ArrayList<>());
                    return dto;
                }).collect(Collectors.toMap(DeptTreeDto::getDeptId, dto -> dto));

        // 修改过滤逻辑：如果父节点不在当前查询结果中，就作为顶层节点返回
        return deptMap.values().stream()
                .filter(dept -> {
                    if (dept.getParentId() != 0) {
                        DeptTreeDto parent = deptMap.get(dept.getParentId());
                        if (parent != null) {
                            parent.getChildren().add(dept);
                            return false;
                        }
                        // 父节点不在查询结果中，将当前节点作为顶层节点
                        return true;
                    }
                    return true;
                }).collect(Collectors.toList());
    }

    @Override
    public Integer add(AddDeptForm form) {

        SysDept parent = baseMapper.selectById(form.getParentId());
        if (parent == null) {
            throw new FjMesException(400, "父部门不存在");
        }

        SysDept dept = BeanUtil.toBean(form, SysDept.class);
        dept.setAncestors(parent.getAncestors() + "," + parent.getDeptId());
        dept.setDelFlag(0+"");
        dept.setCreateTime(LocalDateTime.now());

        // 进行插入操作
        int result = baseMapper.insert(dept);
        if (result == 0) {
            throw new FjMesException(500, "部门添加失败");
        }

        return result;
    }

    @Override
    public Integer edit(SysDept dept) {
        if(dept.getDeptId()==100){
            dept.setUpdateTime(LocalDateTime.now());
            return baseMapper.updateById(dept);
        }
        SysDept parent = baseMapper.selectById(dept.getParentId());
        if (parent == null) {
            throw new FjMesException(400, "父部门不存在");
        }
        dept.setAncestors(parent.getAncestors() + "," + parent.getDeptId());
        dept.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(dept);
    }

    @Override
    public Integer delete(Long deptId, Long userId) {
        SysDept dept = baseMapper.selectById(deptId);
        if (dept != null) {
            // 判断是否有子部门
            List<SysDept> deptList = baseMapper.selectList(new LambdaQueryWrapper<SysDept>().eq(SysDept::getParentId, deptId));
            if (deptList.size() > 0) {
                throw new FjMesException(400, "存在下级部门,不允许删除");
            }
            // 判断部门是否有用户
            Integer count = baseMapper.selectUserListByDeptId(deptId);
            if (count > 0) {
                throw new FjMesException(400, "部门存在用户,不允许删除");
            }
            dept.setDelFlag(2+"");
            dept.setUpdateBy(userId+"");
            dept.setUpdateTime(LocalDateTime.now());
            return baseMapper.updateById(dept);
        }
        return null;
    }

}
